package com.java.computeronline.model.blo;

import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import com.java.computeronline.model.entity.Manufacturer;

public class ManufacturerBLO {
	@SuppressWarnings("unchecked")
	public List<Manufacturer> list(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Manufacturer> manufacturers = null;
		Query query = pm.newQuery(Manufacturer.class);
		manufacturers = (List<Manufacturer>)query.execute();
		return manufacturers;
	}
	
	public Manufacturer getById(Long id){
		Manufacturer manufacturer = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			manufacturer = pm.getObjectById(Manufacturer.class, id);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			pm.close();
		}
		return manufacturer;
	}
	
	public Manufacturer add(Manufacturer manufacturer) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
            pm.makePersistent(manufacturer);
        }catch(Exception ex){
        	ex.printStackTrace();
        } finally {
            pm.close();
        }
		return manufacturer;
	}
	
	public Manufacturer delete(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Manufacturer manufacturer;
		try {
			pm.currentTransaction().begin();
			manufacturer = pm.getObjectById(Manufacturer.class, id);
            pm.deletePersistent(manufacturer);
            pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return manufacturer;
	}
	
	public Manufacturer update(Manufacturer manu){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Manufacturer manufacturer;
		try {
			pm.currentTransaction().begin();
			manufacturer = pm.getObjectById(Manufacturer.class, manu.getId());
			manufacturer.setImage(manu.getImage());
			manufacturer.setName(manu.getName());
			manufacturer.setUrl(manu.getUrl());
            pm.makePersistent(manufacturer);
			pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return manufacturer;
	}
}
